package org.example;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) throws Exception {
        final long start = System.currentTimeMillis();
        int num = 1000000; //  依次增加到100万个数组成员
        for (int i = 1; i <= 10; i++) {
            ArrayListExtend(num);
        }
        long costTime = System.currentTimeMillis() - start;
        System.out.printf("单次平均耗时：%d ms\n", costTime / 10);
    }

    // 动态数组的扩容与内存拷贝性能测试
    static void ArrayListExtend(int arrNum) throws Exception {
        ArrayList<Integer> arrList = new ArrayList<Integer>();
        int extendCount = 0;
        Class<? extends List> strClass = arrList.getClass();
        Field field = strClass.getDeclaredField("elementData");
        try {
            field.setAccessible(true);
        } catch (Exception ignore) {
        }
        Object[] elementData = (Object[]) field.get(arrList);
        int tmpCapacity = elementData.length;
        for (int i = 1; i <= arrNum + 1; i++) {
            arrList.add(i);
            elementData = (Object[]) field.get(arrList);
            if (tmpCapacity != elementData.length) {
                extendCount++;
                System.out.printf("成员个数：%d, 数组出现了扩容：%d ————>%d \n", arrList.size(), tmpCapacity, elementData.length);
                tmpCapacity = elementData.length;
            }
        }

        System.out.printf("累计添加了 %d 个数组元素，扩容次数: %d ,最后一个元素：%d\n", arrNum, extendCount, arrList.get(arrNum - 1));

    }

}